package com.jswlw.service.base.impl;

import com.jswlw.dao.base.MenuMapper;
import com.jswlw.entity.base.Menu;
import com.jswlw.service.base.MenuService;
import com.jswlw.vo.MenuTree;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wu on 2017-12-07.
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    MenuMapper menuMapper;

    public List<Menu> findAll(Map condition) {
        return menuMapper.findAll(condition);
    }

    public Menu findOne(Integer id) {
        return menuMapper.selectByPrimaryKey(id);
    }

    public int insert(Menu menu) {
        return menuMapper.insertSelective(menu);
    }

    public int update(Menu menu) {
        return menuMapper.updateByPrimaryKeySelective(menu);
    }

    public int delete(Integer id) {
        return menuMapper.deleteByPrimaryKey(id);
    }

    public int findCount(Map map) {
        return menuMapper.findCount(map);
    }

    public List<Menu> searchPage(Map map) {
        return null;
    }

    @Override
    public List<MenuTree> createMenuTree() {
        List<Menu> list = menuMapper.findAll(new HashMap());
        if (list != null) {
            return parseMenus(list, 0);
        }
        return null;
    }

    @Override
    public List<Menu> treeList() {
        List<Menu> ret=new ArrayList<>();

        List<Menu> list = menuMapper.findAll(new HashMap());

        return list;
    }

    private String getPname(List<Menu> list, Integer pid){
        for(int i=0;i<list.size();i++){
            if(list.get(i).getId().equals(pid)){
                return list.get(i).getName();
            }
        }
        return "";
    }

    private List<MenuTree> parseMenus(List<Menu> menus, Integer pid) {
        List<MenuTree> menuTrees = new ArrayList<>();
        for (int i = 0; i < menus.size(); i++) {
            Menu menu = menus.get(i);
            if (menu.getPid().equals(pid)) {
                MenuTree menuTree = new MenuTree();
                menuTree.setId(menu.getId());
                menuTree.setText(menu.getName());
                menuTree.setUrl(menu.getUrl());
                menuTrees.add(menuTree);
                List<MenuTree> children = parseMenus(menus, menu.getId());
                if (children.size() > 0)
                    menuTree.setNodes(children);
            }
        }
        return menuTrees;
    }

    @Override
    public List<MenuTree> findMenu4Role(Integer roleId) {

        if(roleId==1){
            List<Menu> menus=menuMapper.findAll(new HashMap());
            return parseMenus(menus, 0);
        }else{
            List<Menu> menus=menuMapper.findMenu4Role(roleId);
            return parseMenus(menus, 0);
        }

    }
}
